10. 2D Vectors and For Loops

2D Vectors and For Loops

Because 2D vectors are just vectors inside a vector, a 2D vector has the same methods as a 1D vector.

That way the cout code from the example works:

for (int row = 0; row < twodvector.size(); row++) {
        for (int column = 0; column < twodvector[0].size(); column++) {
            cout << twodvector[row][column] << " ";
        }
        cout << endl;

When you type twodvector.size(), that will give you the size of the outside vector. The outside vector had five elements, which represents the number of rows in the matrix being represented:

{2 2 2} 
{2 2 2} 
{2 2 2} 
{2 2 2} 
{2 2 2}

When you write twodvector[0].size(), you are taking the first element of the outside vector, [2 2 2], and asking for the size of that vector, which in this case is three. So essentially the for loop is saying:

for (int row = 0; row < 5; row++) {
        for (int column = 0; column < 3; column++) {
            cout << twodvector[row][column] << " ";
        }
        cout << endl;